package utfpr.gang5.hermes.controledepresenca.cliente.swt;

import java.rmi.RemoteException;

import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.StatusLineManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

import utfpr.gang5.hermes.controledepresenca.cliente.RmiServiceFactory;
import utfpr.gang5.hermes.controledepresenca.pojo.Aluno;
import utfpr.gang5.hermes.controledepresenca.pojo.Disciplina;
import org.eclipse.swt.layout.GridData;

public class TelaPrincipal extends ApplicationWindow {

	private Object usuario;
	private Disciplina disciplinaAtual;
	private Label lbMensagem;
	private Label lbPresenca;
	private Thread thread;

	/**
	 * Create the application window.
	 */
	public TelaPrincipal() {
		super(null);
		createActions();
		addToolBar(SWT.FLAT | SWT.WRAP);
		addMenuBar();
		addStatusLine();
	}

	/**
	 * Create contents of the application window.
	 * 
	 * @param parent
	 */
	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(1, false));

		lbMensagem = new Label(container, SWT.NONE);
		GridData gd_lbMensagem = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_lbMensagem.widthHint = 300;
		lbMensagem.setLayoutData(gd_lbMensagem);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		{
			lbPresenca = new Label(container, SWT.NONE);
			GridData gd_lbPresenca = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
			gd_lbPresenca.widthHint = 300;
			lbPresenca.setLayoutData(gd_lbPresenca);
		}
		
		thread = new Thread() {
			public void run() {
				while (true) {
		
					verificarDisciplinaAtual();
					verificarPresenca();

					try {
						sleep(1000 * 60);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			};
		};
		thread.start();
		return container;
	}

	private boolean verificarPresenca() {
		try {
			final boolean presente = RmiServiceFactory.getService().verificarPresenca(
					(Aluno) usuario);
			
			getShell().getDisplay().asyncExec(new Runnable() {

				@Override
				public void run() {
					if (lbPresenca != null && !lbPresenca.isDisposed()) {
						lbPresenca.setText((!presente  ? "Você ainda não ganhou presença"
																: "Você já ganhou presença nessa disciplina!"));
					}
				}
			});
			
			return presente;
			
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void create() {
		super.create();
	}
	
	@Override
	public boolean close() {
		if (thread != null) {
			if (thread.isAlive())
				thread.stop();
		}
		return super.close();
	}
	

	@Override
	public int open() {
		LoginDialog loginDialog = new LoginDialog(getShell());
		loginDialog.open();

		if (!loginDialog.isLogou()) {
			close();
			return 0;
		}

		usuario = loginDialog.getUsuario();
		
		int ret = super.open();

		return ret;

	}

	private void verificarDisciplinaAtual() {
		try {
			disciplinaAtual = RmiServiceFactory.getService()
					.buscarDisciplinaAtual((Aluno) usuario);
			
			getShell().getDisplay().asyncExec(new Runnable() {

				@Override
				public void run() {
					if (lbMensagem != null && !lbMensagem.isDisposed()) {
						lbMensagem
							.setText((disciplinaAtual != null ? "Olá " + ((Aluno)usuario).getNome() + ", você está na disciplina "
									+ disciplinaAtual.getNome()
									: "Olá " + ((Aluno)usuario).getNome() + ", você não está em nenhuma disciplina"));
					}
				}
			});
			
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * Create the actions.
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Create the menu manager.
	 * 
	 * @return the menu manager
	 */
	@Override
	protected MenuManager createMenuManager() {
		MenuManager menuManager = new MenuManager("menu");
		return menuManager;
	}

	/**
	 * Create the toolbar manager.
	 * 
	 * @return the toolbar manager
	 */
	@Override
	protected ToolBarManager createToolBarManager(int style) {
		ToolBarManager toolBarManager = new ToolBarManager(style);
		return toolBarManager;
	}

	/**
	 * Create the status line manager.
	 * 
	 * @return the status line manager
	 */
	@Override
	protected StatusLineManager createStatusLineManager() {
		StatusLineManager statusLineManager = new StatusLineManager();
		return statusLineManager;
	}

	/**
	 * Launch the application.
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {

			TelaPrincipal window = new TelaPrincipal();
			window.setBlockOnOpen(true);
			window.open();
			Display.getCurrent().dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Configure the shell.
	 * 
	 * @param newShell
	 */
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("New Application");
	}

	/**
	 * Return the initial size of the window.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(366, 253);
	}
}
